<template>
    <div>
        <!--查询-->
        <div style="margin: 10px 0" v-if="admin">
            <el-input
                style="width: 150px"
                placeholder="请输入用户名"
                suffix-icon="el-icon-search"
                v-model="userName"
            ></el-input>
            <el-select v-model="status" placeholder="请选择状态" style="width: 150px">
                <el-option
                    v-for="item in item"
                    :label="item.value"
                    :value="item.value">
                </el-option>
            </el-select>
            <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
            <el-button type="warning" @click="reset">重置</el-button>
        </div>
        
        <div style="margin: 10px 0">
            <el-popconfirm v-if="admin"
                           class="ml-5"
                           confirm-button-text='确定'
                           cancel-button-text='我再想想'
                           icon="el-icon-info"
                           icon-color="red"
                           title="您确定批量删除这些数据吗？"
                           @confirm="delBatch"
            >
                <el-button type="danger" slot="reference">批量删除 <i class="el-icon-remove-outline"></i></el-button>
            </el-popconfirm>
            <el-button type="primary" class="ml-5" @click="exp">导出 <i class="el-icon-download"></i></el-button>
        </div>
        
        <!--表格-->
        <el-table :data="tableData" border stripe :header-cell-class-name="'headerBg'"
                  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
            <el-table-column prop="fullname" label="用户全名"></el-table-column>
            <el-table-column prop="orderTime" label="订单创建时间"></el-table-column>
            <el-table-column prop="ticketId" label="关联车票ID"></el-table-column>
            <el-table-column prop="userId" label="用户ID"></el-table-column>
            <el-table-column prop="orderStatus" label="订单状态">
                <template slot-scope="scope">
                    <el-tag :type="getOrderType(scope.row.orderStatus)">
                        {{ scope.row.orderStatus }}
                    </el-tag>
                </template>
            </el-table-column>
            
            <el-table-column label="操作" width="280" align="center">
                
                <template slot-scope="scope">
                    <el-button type="success" @click="seeTicket(scope.row)">
                        查看票据详情
                        <i class="el-icon-edit"></i>
                    </el-button>
                    
                    <!--用户操作-->
                    <el-popconfirm
                        v-if="!admin&&scope.row.orderStatus==='已支付'"
                        class="ml-5"
                        confirm-button-text='确定'
                        cancel-button-text='我再想想'
                        icon="el-icon-info"
                        icon-color="red"
                        title="您确定要退票吗？"
                        @confirm="handleEdit(scope.row,'退票受理中')"
                    >
                        <el-button type="danger" slot="reference">
                            退票
                            <i class="el-icon-edit"></i>
                        </el-button>
                    </el-popconfirm>
                    <el-popconfirm
                        v-if="!admin&&scope.row.orderStatus==='已退票'"
                        class="ml-5"
                        confirm-button-text='确定'
                        cancel-button-text='我再想想'
                        icon="el-icon-info"
                        icon-color="red"
                        title="您确定删除吗？"
                        @confirm="del(scope.row.id)"
                    >
                        <el-button
                            type="danger"
                            slot="reference"
                            :disabled="scope.row.orderStatus==='退票受理中'"
                        >
                            删除
                            <i class="el-icon-remove-outline"></i>
                        </el-button>
                    </el-popconfirm>
                    
                    
                    <!--管理员删除按钮-->
                    <el-popconfirm
                        v-if="admin&&scope.row.orderStatus!=='退票受理中'"
                        class="ml-5"
                        confirm-button-text='确定'
                        cancel-button-text='我再想想'
                        icon="el-icon-info"
                        icon-color="red"
                        title="您确定删除吗？"
                        @confirm="del(scope.row.id)"
                    >
                        <el-button type="danger" slot="reference">删除 <i class="el-icon-remove-outline"></i>
                        </el-button>
                    </el-popconfirm>
                    <el-popconfirm
                        v-if="admin&&scope.row.orderStatus==='退票受理中'"
                        class="ml-5"
                        confirm-button-text='确定'
                        cancel-button-text='我再想想'
                        icon="el-icon-info"
                        title="审核通过？"
                        @confirm="handleEdit(scope.row,'已退票')"
                    >
                        <el-button type="warning" slot="reference">处理 <i class="el-icon-remove-outline"></i>
                        </el-button>
                    </el-popconfirm>
                
                </template>
            </el-table-column>
        </el-table>
        <div style="padding: 10px 0">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageNum"
                :page-sizes="[2, 5, 10, 20]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
        
        <el-dialog title="信息" :visible.sync="dialogFormVisible" width="30%">
            <el-form label-width="80px" size="small">
                <el-form-item label="用户全名">
                    <el-input v-model="form.fullname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="订单时间">
                    <el-date-picker v-model="form.orderTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                                    placeholder="选择日期时间"></el-date-picker>
                </el-form-item>
                <el-form-item label="关联车票ID">
                    <el-input v-model="form.ticketId" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户ID">
                    <el-input v-model="form.userId" autocomplete="off"></el-input>
                </el-form-item>
            
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 票据详情模态框 -->
        <el-dialog title="票据详情" :visible.sync="ticketDialogVisible" width="50%">
            <el-form label-width="80px" size="small">
                <el-form-item label="票据ID">
                    <el-input v-model="ticketDetails.id" disabled></el-input>
                </el-form-item>
                <el-form-item label="列车ID">
                    <el-input v-model="ticketDetails.trainId" disabled></el-input>
                </el-form-item>
                <el-form-item label="车厢号">
                    <el-input v-model="ticketDetails.carriageNumber" disabled></el-input>
                </el-form-item>
                <el-form-item label="座位号">
                    <el-input v-model="ticketDetails.seatNumber" disabled></el-input>
                </el-form-item>
                <!--                <el-form-item label="票务状态">-->
                <!--                    <el-select v-model="ticketDetails.ticketStatus" placeholder="请选择票务状态">-->
                <!--                        &lt;!&ndash;            <el-option label="改签" value="改签"></el-option>&ndash;&gt;-->
                <!--                        <el-option label="退票" value="退票"></el-option>-->
                <!--                    </el-select>-->
                <!--                </el-form-item>-->
                <!-- 其他票据详情字段 -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="ticketDialogVisible = false">关 闭</el-button>
            </div>
        </el-dialog>
    
    </div>
</template>

<script>

export default {
    name: "TbOrder",
    data() {
        return {
            tableData: [],
            total: 0,
            pageNum: 1,
            pageSize: 10,
            userId: "",
            userName: "",
            status: "",
            item: [{value: '已支付'}, {value: '已退票'},{value: '退票受理中'}],
            form: {},
            dialogFormVisible: false,
            multipleSelection: [], ticketDialogVisible: false,
            ticketDetails: {},  // 用于存储票据详情
            startStatus: null,
            user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
            admin: false,
        }
    },
    created() {
        this.load()
        this.admin = this.user.role.includes("ADMIN");
    },
    methods: {
        handleEdit(order, status) {
            order.orderStatus = status;
            this.request.post("/tbOrder", order).then(() => {
                this.load();
            });
            this.$message.success("操作成功");
        },
        getOrderType(status) {
            switch (status) {
                case '已支付':
                    return 'success';
                case '已退票':
                    return 'danger';
                case '退票受理中':
                    return 'warning';
                default:
                    return 'info';
            }
        },
        seeTicket(row) {
            this.request.get("/tbTicket/" + row.ticketId).then(res => {
                this.startStatus = res.data.ticketStatus;
                this.ticketDetails = res.data;  // 设置票据详情
                this.ticketDialogVisible = true;  // 打开对话框
                this.ticketDetails = res.data;
            })
        },
        load() {
            // user.role!=='ROLE_ADMIN'  ,判断是否为管理员、如果不是管理员，则是普通用户。this.name=this.user.id;通过该参数查询用户的订单
            if (this.user.role !== 'ROLE_ADMIN' && this.user.role !== 'ROLE_TRAIN_ADMIN') {
                this.userId = this.user.id;
            }
            this.request.get("/tbOrder/page", {
                params: {
                    userId: this.userId,
                    userName: this.userName,
                    status: this.status,
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                }
            }).then(res => {
                this.tableData = res.data.records
                this.total = res.data.total
            })
        },
        reset() {
            this.userName = "";
            this.status = "";
            
            this.load();
        },
        save() {
            this.request.post("/tbOrder", this.form).then(res => {
                if (res.code === '200') {
                    this.$message.success("保存成功")
                    this.dialogFormVisible = false
                    this.load()
                } else {
                    this.$message.error("保存失败")
                }
            })
        },
        handleAdd() {
            this.dialogFormVisible = true
            this.form = {}
            this.$nextTick(() => {
                if (this.$refs.img) {
                    this.$refs.img.clearFiles();
                }
                if (this.$refs.file) {
                    this.$refs.file.clearFiles();
                }
            })
        },
        del(id) {
            this.request.delete("/tbOrder/" + id).then(res => {
                if (res.code === '200') {
                    this.$message.success("删除成功")
                    this.load()
                } else {
                    this.$message.error("删除失败")
                }
            })
        },
        handleSelectionChange(val) {
            this.multipleSelection = val
        },
        delBatch() {
            let ids = this.multipleSelection.map(v => v.id)  // [{}, {}, {}] => [1,2,3]
            this.request.post("/tbOrder/del/batch", ids).then(res => {
                if (res.code === '200') {
                    this.$message.success("批量删除成功")
                    this.load()
                } else {
                    this.$message.error("批量删除失败")
                }
            })
        },
        handleSizeChange(pageSize) {
            this.pageSize = pageSize
            this.load()
        },
        handleCurrentChange(pageNum) {
            this.pageNum = pageNum
            this.load()
        },
        exp() {
            this.request.get("/tbOrder/export", {
                responseType: 'blob'  // 设置响应类型为blob
            }).then(res => {
                // 创建Blob对象
                const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
                // 创建下载链接
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                // 设置文件名
                link.download = '订单信息.xlsx';
                // 触发点击事件
                link.click();
                // 释放URL对象
                window.URL.revokeObjectURL(link.href);
                this.$message.success("导出成功");
            }).catch(error => {
                this.$message.error("导出失败");
                console.error('导出失败:', error);
            });
        },
        handleExcelImportSuccess() {
        },
    }
}
</script>


<style>
.headerBg {
    background: #eee !important;
}
</style>
